<!-- 新增关注 -->
<template>
    <MessageList 
        title="新增关注"
        :messageList="messageList"
        :unreadCount="unreadCount"
        @item-click="handleItemClick"
    />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import MessageList from '@/components/MessageList.vue';

const router = useRouter();
const messageList = ref([]);
const unreadCount = ref(0);

// 从本地存储加载已读状态
const loadReadStatus = () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) return {};
        
        const readStatus = localStorage.getItem(`followReadStatus_${userId}`) || '{}';
        return JSON.parse(readStatus);
    } catch (error) {
        console.error('加载关注已读状态失败:', error);
        return {};
    }
};

// 保存已读状态到本地存储
const saveReadStatus = (readStatus) => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) return;
        
        localStorage.setItem(`followReadStatus_${userId}`, JSON.stringify(readStatus));
    } catch (error) {
        console.error('保存关注已读状态失败:', error);
    }
};

// 标记消息为已读
const markAsRead = (messageId) => {
    const readStatus = loadReadStatus();
    readStatus[messageId] = true;
    saveReadStatus(readStatus);
    
    // 更新消息列表中的已读状态
    const message = messageList.value.find(msg => msg.id === messageId);
    if (message) {
        message.isRead = true;
    }
    
    // 重新计算未读数量
    calculateUnreadCount();
};

// 计算未读消息数量
const calculateUnreadCount = () => {
    const readStatus = loadReadStatus();
    unreadCount.value = messageList.value.filter(msg => !readStatus[msg.id]).length;
    
    // 保存未读数量到localStorage，供News页面使用
    try {
        const userId = localStorage.getItem('user_id');
        if (userId) {
            localStorage.setItem(`followUnreadCount_${userId}`, unreadCount.value.toString());
        }
    } catch (error) {
        console.error('保存关注未读数量失败:', error);
    }
};

// 生成消息唯一ID
const generateMessageId = (followerId) => {
    return `follow_${followerId}`;
};

// 获取关注列表
const fetchFollowList = async () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) {
            console.error('用户ID不存在');
            return;
        }

        const response = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}/followers`);
        if (response.data.success) {
            const followingList = response.data.data.followers;
            console.log('获取到关注列表:', followingList);
            
            // 获取每个关注用户的详细信息
            await fetchUserDetails(followingList);
        } else {
            console.error('获取关注列表失败:', response.data.message);
        }
    } catch (error) {
        console.error('获取关注列表出错:', error);
    }
};

// 获取用户详细信息
const fetchUserDetails = async (followingList) => {
    try {
        const readStatus = loadReadStatus();
        const allFollows = [];
        
        for (const followerId of followingList) {
            try {
                const response = await axios.get(`http://1.14.98.17:8765/api/users/${followerId}`);
                if (response.data.success) {
                    const userData = response.data.data;
                    console.log(`用户 ${followerId} 的详细信息:`, userData);
                    
                    const messageId = generateMessageId(followerId);
                    const followMessage = {
                        id: messageId,
                        userId: followerId,
                        img: userData.avatar_url || '',
                        title: userData.nickname || '未设置昵称',
                        content: '关注了你',
                        time: '', // 这里不需要时间，显示固定文本
                        isRead: readStatus[messageId] || false
                    };
                    
                    allFollows.push(followMessage);
                }
            } catch (error) {
                console.error(`获取用户 ${followerId} 信息失败:`, error);
            }
        }
        
        messageList.value = allFollows;
        calculateUnreadCount();
        console.log('最终关注消息列表:', messageList.value);
        console.log('未读关注消息数量:', unreadCount.value);
    } catch (error) {
        console.error('获取用户详细信息出错:', error);
    }
};

// 处理点击事件
const handleItemClick = (item) => {
    console.log('点击了关注消息项:', item);
    
    // 标记消息为已读
    markAsRead(item.id);
    
    // 跳转到用户详情页面
    router.push({
        name: 'usercont',
        query: {
            userId: item.userId
        }
    });
};

onMounted(() => {
    fetchFollowList();
});
</script>
